package com.adou.multi.multi_tenancy.interceptor;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

import com.adou.multi.multi_tenancy.util.TeanantContext;
/**
 * 拦截器
 * @author ADou
 *
 */
@Component
public class TenantInterceptor implements WebRequestInterceptor {
	private final String defaultTenant;
	
	@Autowired
	public TenantInterceptor(@Value("${multitenancy.tenant.default-tenant:#{null}}") String defaultTenant){
		this.defaultTenant = defaultTenant;
	}
	
	@Override
	public void afterCompletion(@NotNull WebRequest req, Exception model) throws Exception {

	}

	@Override
	public void postHandle(@NotNull WebRequest req, ModelMap model) throws Exception {
		TeanantContext.clear();
	}

	@Override
	public void preHandle(WebRequest req) throws Exception {
		String tenantId;
		if(req.getHeader("X-TENANT-ID") != null){
			tenantId = req.getHeader("X-TENANT-ID");
		} else if (this.defaultTenant != null){
			tenantId = this.defaultTenant;
		} else {
			tenantId = ((ServletWebRequest)req).getRequest().getServerName().split("\\.")[0];
		}
		TeanantContext.setTenantId(tenantId);
	}

}
